package model

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	"time"
)

type IAdminUserIdContainer interface {
	GetUserIds() []int64
}

type AdminUser struct {
	Id         int64     `xorm:"pk autoincr" form:"-"`
	Username   string    `valid:"Required;MaxSize(30);AlphaDash;"`
	Password   string    `valid:"Required;MaxSize(20);MinSize(6);AlphaNumeric"`
	FromUserId int64     `form:"-"`
	Name       string    `valid:"Required;MaxSize(20)"`
	Email      string    `valid:"Required;Email"`
	Phone      string    `valid:"Required;MaxSize(20);Numeric"`
	CreateTime time.Time `xorm:"created" form:"-"`
}

type MapAdminUser map[int64]*AdminUser

func GetUserFromUserIdContainer(userIdContainer IAdminUserIdContainer) (MapAdminUser, error) {
	userIds := userIdContainer.GetUserIds()
	users := make(MapAdminUser)

	if len(userIds) <= 0 {
		return users, nil
	}

	err := Orm.In("id", userIds).Find(&users)
	if err != nil {
		return nil, err
	}

	return users, nil
}

func GetAdminUserById(id int64) (*AdminUser, error) {
	if id <= 0 {
		return nil, errors.New("id empty")

	}

	adminUser := new(AdminUser)
	ok, err := Orm.Id(id).Get(adminUser)
	if err != nil {
		return nil, err
	}

	if ok {
		return adminUser, nil
	} else {
		return nil, ErrNotExist
	}
}

func GetAdminUserByUserName(username string) (*AdminUser, error) {
	if username == "" {
		return nil, errors.New("username empty")
	}

	adminUser := &AdminUser{}
	ok, err := Orm.Where("`username`=?", username).Get(adminUser)
	if err != nil {
		return nil, err
	}

	if !ok {
		return nil, ErrNotExist
	}

	return adminUser, nil
}

func GetAdminUserByUserNamePass(username, password string) (*AdminUser, error) {
	if username == "" || password == "" {
		return nil, errors.New("username or password empty")
	}
	adminUser := new(AdminUser)

	h := md5.New()
	h.Write([]byte(password))

	ok, err := Orm.Where("`username`=? AND `password`=?", username, hex.EncodeToString(h.Sum(nil))).Get(adminUser)
	if err != nil {
		return nil, err
	}

	if !ok {
		return nil, errors.New("No record")
	}

	return adminUser, nil
}

func SearchAdminUserByUserName(username string, offset, limit int) ([]AdminUser, error) {
	adminUsers := make([]AdminUser, 0)
	if username == "" {
		return nil, errors.New("username empty")
	}
	err := Orm.Where("`username` LIKE ?", username+"%").Limit(limit, offset).Find(&adminUsers)
	if err != nil {
		return nil, err
	}

	return adminUsers, nil
}

func AdminUserPasswordHash(p string) string {
	if p == "" {
		return ""
	}

	h := md5.New()
	h.Write([]byte(p))

	return hex.EncodeToString(h.Sum(nil))
}
